package com.ones.kit.redis.autoconfigure;

import cn.hutool.core.util.ReflectUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ones.kit.redis.jackson.OnesJavaTimeModule;
import com.ones.kit.redis.util.OnesRedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * Redis配置
 *
 * @author Clark
 * @version 2024-11-22
 */
@Slf4j
@Lazy
@AutoConfiguration
@ConditionalOnProperty(value = "spring.data.redis.host")
public class OnesRedisAutoConfiguration {

    /**
     * redisTemplate
     * @param factory RedisConnectionFactory
     * @return RedisTemplate
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        // 参照pigx v5.6
        RedisTemplate<String, Object> template = new RedisTemplate();
        // key采用String的序列化方式
        template.setKeySerializer(RedisSerializer.string());
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(RedisSerializer.string());
        // 设置 redisTemplate 的序列化器为 json
        RedisSerializer<Object> jsonRedisSerializer = RedisSerializer.json();
        ObjectMapper objectMapper = (ObjectMapper) ReflectUtil.getFieldValue(jsonRedisSerializer, "mapper");
        objectMapper.registerModules(new OnesJavaTimeModule());
        template.setValueSerializer(jsonRedisSerializer);
        template.setHashValueSerializer(jsonRedisSerializer);

        template.setConnectionFactory(factory);
        return template;
//        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
//        // value序列化方式采用jackson
//        template.setValueSerializer(jackson2JsonRedisSerializer);
//        // hash的value序列化方式采用jackson
//        template.setHashValueSerializer(jackson2JsonRedisSerializer);
//        template.afterPropertiesSet();
//        return template;
    }

    /**
     * 构建
     * @return OnesRedisUtils
     */
    @Bean
    @DependsOn("redisTemplate")
    public OnesRedisUtils onesRedisUtils() {
        OnesRedisUtils utils = new OnesRedisUtils();
        log.warn("******************* Redis工具类自动装配完成 *******************");
        return utils;
    }
}